package com.shangjinrong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangjinrong.domain.Borrower;
import com.shangjinrong.domain.BorrowerAttach;
import com.shangjinrong.domain.UserInfo;
import com.shangjinrong.domain.UserIntegral;
import com.shangjinrong.domain.vo.BorrowerApprovalVO;
import com.shangjinrong.domain.vo.BorrowerAttachVO;
import com.shangjinrong.domain.vo.BorrowerDetailVO;
import com.shangjinrong.domain.vo.BorrowerVO;
import com.shangjinrong.enums.BorrowerStatusEnum;
import com.shangjinrong.enums.IntegralEnum;
import com.shangjinrong.enums.UserBindEnum;
import com.shangjinrong.excption.Assert;
import com.shangjinrong.mapper.BorrowerAttachMapper;
import com.shangjinrong.mapper.BorrowerMapper;
import com.shangjinrong.mapper.UserInfoMapper;
import com.shangjinrong.mapper.UserIntegralMapper;
import com.shangjinrong.result.ResponseEnum;
import com.shangjinrong.service.BorrowerAttachService;
import com.shangjinrong.service.BorrowerService;
import com.shangjinrong.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.ZoneId;
import java.util.List;

@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {
    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Autowired
    private BorrowerAttachService borrowerAttachService;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Autowired
    private DictService dictService;

    @Resource
    private UserIntegralMapper userIntegralMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowerByUserId(BorrowerVO borrowerVO, Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);

        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus().byteValue());
        baseMapper.insert(borrower);    //添加借款人信息

        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> borrowerAttach.setBorrowerId(borrower.getId()));
        borrowerAttachMapper.insertList(borrowerAttachList);    //添加借款人上传资源

        userInfo.setBindStatus(BorrowerStatusEnum.AUTH_RUN.getStatus().byteValue());
        userInfoMapper.updateById(userInfo);    //更新会员状态为认证中

    }

    @Override
    public BorrowerDetailVO getBorrowerDetailVoById(Long id) {
        Borrower borrower = baseMapper.selectById(id);

        BorrowerDetailVO borrowerDetailVo = new BorrowerDetailVO();

        BeanUtils.copyProperties(borrower, borrowerDetailVo);

        borrowerDetailVo.setCreateTime(borrower.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());

        //是否结婚
        borrowerDetailVo.setIsMarry(borrower.getIsMarry() ? "是" : "否");
        borrowerDetailVo.setSex(borrower.getSex() == 1 ? "男" : "女");

        //下拉列表
        borrowerDetailVo.setEducation(dictService.getNameByParentDictCodeAndValue("education", borrower.getEducation().intValue()));
        borrowerDetailVo.setIndustry(dictService.getNameByParentDictCodeAndValue("industry", borrower.getIndustry().intValue()));
        borrowerDetailVo.setIncome(dictService.getNameByParentDictCodeAndValue("income", borrower.getIncome().intValue()));
        borrowerDetailVo.setReturnSource(dictService.getNameByParentDictCodeAndValue("returnSource", borrower.getReturnSource().intValue()));
        borrowerDetailVo.setContactsRelation(dictService.getNameByParentDictCodeAndValue("relation", borrower.getContactsRelation().intValue()));


        //审批状态
        String status = BorrowerStatusEnum.getMsgByStatus(borrower.getStatus().intValue());
        borrowerDetailVo.setStatus(status);

        //附件列表
        List<BorrowerAttachVO> borrowerAttachVOList = borrowerAttachService.selectBorrowerAttachVoList(id);
        borrowerDetailVo.setBorrowerAttachVOList(borrowerAttachVOList);

        return borrowerDetailVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        //更新借款人认证状态
        Borrower borrower = baseMapper.selectById(borrowerApprovalVO.getBorrowerId());
        borrower.setStatus(borrowerApprovalVO.getStatus().byteValue());
        baseMapper.updateById(borrower);

        long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //添加基本信息积分
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setContent("借款人基本信息");
        userIntegralMapper.insert(userIntegral);

        int integral = userInfo.getIntegral() + borrowerApprovalVO.getInfoIntegral();

        //身份证信息积分
        if (borrowerApprovalVO.getIsIdCardOk()) {
            integral += IntegralEnum.BORROWER_IDCARD.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        //房产信息积分
        if (borrowerApprovalVO.getIsHouseOk()) {
            integral += IntegralEnum.BORROWER_HOUSE.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        //车辆信息积分
        if (borrowerApprovalVO.getIsCarOk()) {
            integral += IntegralEnum.BORROWER_CAR.getIntegral();
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralMapper.insert(userIntegral);
        }

        //更新用户积分和审核状态
        userInfo.setIntegral(integral);
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus().byteValue());
        userInfoMapper.updateById(userInfo);

    }

    @Override
    public Integer getStatus(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //用户绑定状态
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.OK_BIND.getStatus()
                , ResponseEnum.USER_NO_BIND_ERROR);

        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper();
        wrapper.eq(Borrower::getUserId,userId);
        Borrower borrower = baseMapper.selectOne(wrapper);
        if(null == borrower){
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        return borrower.getStatus().intValue();
    }

    @Override
    public void paging(Page page,String keyword) {
        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Borrower::getName,keyword).or()
                .like(Borrower::getIdCard,keyword).or()
                .like(Borrower::getMobile,keyword);
        baseMapper.selectPage(page,wrapper);
    }

}
